package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.getProperty
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiSyncDemo* @Description:系统API接口开发Demo ，重点关注业务逻辑部分
 * @author: LiJuntao* @date 2021-07-13 23:58:55
 *
 */

public class apiWXCodeChat implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWXCodeChat.class);
    private static final String DOMAIN = getProperty.get("NGS.Domain");

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);
        String dataSourceID = "dataSource";

        //获取所有参数名
        Enumeration e = request.getParameterNames();
        while (e.hasMoreElements()) {
            //获取当前参数名
            String parameterName = (String) e.nextElement();
            //再通过request.getParameter("")的方法来获取对应参数名的值
            log.debug(parameterName + ": " + request.getParameter(parameterName));
        }

        String code = request.getParameter("code");
        String state = request.getParameter("state");

        // 调用微信获取OPENID
        JSONObject apiTokenJson = JSONObject.parseObject(Util.doHttpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + getProperty.get("3VWX-SOFT.APPID") + "&secret=" + getProperty.get("3VWX-SOFT.APPSECRET")
                + "&code=" + code + "&grant_type=authorization_code", "UTF-8", 5000, 0));

        String access_token = apiTokenJson.getString("access_token");
        int expires_in = apiTokenJson.getInteger("expires_in");
        String refresh_token = apiTokenJson.getString("refresh_token");
        String openid = apiTokenJson.getString("openid");
        String scope = apiTokenJson.getString("scope");

        String linkURL = getProperty.get("3VWX-SOFT.CHATURL") + "&vid=" + openid;

        response.sendRedirect(linkURL);
    }
}